package com.db.designpatterns.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.db.designpatterns.connector.Connector;
import com.db.designpatterns.connector.ServerConnector;

public class LocalServerCache implements ServerCache {

	private ServerConnector serverConnector;
	private Map<String,Object> cache = new HashMap<>();
	private List<Connector> connectors = new ArrayList<>();
	
	public LocalServerCache(ServerConnector serverConnector) {
		this.serverConnector = serverConnector;
		serverConnector.connectionListen(new ConnectorListener() {
			
			@Override
			public void connectionListener(Connector connector) {
				connect(connector);
			}
			
		});
	}
	@Override
	public Object get(String name) {
		throw new UnsupportedOperationException();
	}

	@Override
	public void put(String name, Object o) {
		cache.put(name, o);
		for(Connector connector : connectors) {
			connector.send(name,o);
		}
	}

	@Override
	public void connect(Connector connector) {
		if(!connectors.contains(connector)) {
			connectors.add(connector);			
		}
	}
	
}
